/*
 * @Author: liu.lin liu.lin@hzleaper.com
 * @Date: 2023-11-16 16:50:46
 * @LastEditors: liu.lin liu.lin@hzleaper.com
 * @LastEditTime: 2023-11-23 10:26:50
 * @FilePath: \aoi_link_frontend\src\page\fpy-analyse\components\TableList\index.tsx
 * @Description: 这是table组件
 */
import { Pagination, Spin, Table } from 'antd';
import React, { useEffect, useState } from 'react';
import { DataSourceType, FathertableDatasType, SontableDatasType } from './index.type';
import { useNavigate } from 'react-router-dom';
import { FC } from 'react';
import './index.less';
import { ColumnsType } from 'antd/es/table';
import { use } from 'echarts';

type TableListsProp = {
  pageSize: number;
  pageNum: number;
  fatherColumns: ColumnsType<FathertableDatasType>;
  sonColumns: ColumnsType<SontableDatasType>;
  dataSource: DataSourceType;
  tableLoading: boolean;
  handleChangePage: (page: number, pageSize: number) => void;
};

const TableLists: FC<TableListsProp> = (props: TableListsProp) => {
  const navigate = useNavigate();
  const [fatherColumn, setFatherColumn] = useState<ColumnsType<FathertableDatasType>>([]);
  const [sonColumn, setSonColumn] = useState<ColumnsType<SontableDatasType>>([]);
  const [fathertableDatas, setFatherTableDatas] = useState<FathertableDatasType[]>([]);
  const [sonableDatas, setSonTableDatas] = useState<SontableDatasType[]>([]);
  const [page, setPage] = useState(1); //当前页码
  const [pageSize, setPageSize] = useState(0); //当前页码展示数量
  const [tableLoading, setTableLoading] = useState(false);
  const [total, setTotal] = useState(0);

  useEffect(() => {
    setFatherColumn(props.fatherColumns);
  }, [props.fatherColumns]);

  useEffect(() => {
    setPageSize(props.pageSize);
  }, [props.pageSize]);

  useEffect(() => {
    setPage(props.pageNum);
  }, [props.pageNum]);

  useEffect(() => {
    setSonColumn(props.sonColumns);
  }, [props.sonColumns]);

  useEffect(() => {
    setTableLoading(props.tableLoading);
  }, [props.tableLoading]);

  //  两个数据变动问题（注意：小心bug）问题已经排查，改动了原数据。
  useEffect(() => {
    const { list, total } = props.dataSource;
    console.log(`list`, list);
    setTotal(total);
    setFatherTableDatas(handlePropsFatherDataSource(list));
    setSonTableDatas(handlePropsSonDataSource(list));
  }, [props.dataSource]);

  /**
   * @description: 处理传过来的数据逻辑
   * 1 先计算二级分类（工位的长度）
   * 2 再计算一级分类（工站的长度）
   * @param {any} arr
   * @return {*}
   */
  const handlePropsSonDataSource = (arr: any[]) => {
    const newDatas: any[] = [];
    if (arr.length === 0) return [];
    try {
      arr.map((item, index) => {
        if (item.children) {
          Object.keys(item.children).forEach((key, ti) => {
            Object.keys(item.children[key]).forEach((k, ki) => {
              let twoRowSpan = 0;
              twoRowSpan = item.children[key][k].length;
              if (!Array.isArray(item.children[key])) {
                item.children[key][k].map((ss, si) => {
                  // console.log(` item.children[key]`, item.children[key][k]);

                  if (si === 0) {
                    ss.twoRowSpan = twoRowSpan;
                  }
                  if (si === 0 && ki === 0) {
                    // 动态计算oneRowSpan的长度
                    const values = Object.values(item.children[key]);
                    const sum = values.reduce((acc: number, arr) => {
                      if (Array.isArray(arr)) {
                        return acc + arr.length;
                      } else {
                        return acc;
                      }
                    }, 0);
                    ss.oneRowSpan = sum;
                  }
                  newDatas.push(ss);
                });
              } else {
                newDatas.push(...item.children[key]);
              }
            });
            // console.log(`item.children[${key}]`, item.children[key]); //工位
          });
        } else {
          // console.log(`数据丢失`, fathertableDatas, sonableDatas, props.dataSource);
        }
      });
    } catch (error) {
      console.log(`error`, error);
    }
    console.log(`newDatas`, newDatas);

    return newDatas;
  };

  /**
   * @description: 父级表格数据
   * @param {any} arr
   * @return {*}
   */
  const handlePropsFatherDataSource = (arr: any[]) => {
    const newDatas: FathertableDatasType[] = [];
    arr.map(item => {
      const newItem = { ...item };
      delete newItem.children;
      newDatas.push(newItem);
    });
    // console.log(newDatas);

    return newDatas;
  };

  /**
   * @description:执行父组件的逻辑
   * @param {number} page
   * @param {number} pageSize
   * @return {*}
   */
  const handleChangePage = (page: number, pageSize: number) => {
    setPage(page);
    props.handleChangePage(page, pageSize);
  };

  const expandedRowRender = (record, index, indent, expanded) => {
    const filterDatas = sonableDatas.filter(item => item.lotId === record.lotId);
    return <Table columns={sonColumn} bordered rowKey={record => record.uuid} dataSource={filterDatas} scroll={{ y: 300 }} pagination={false} />;
  };

  return (
    <div className="table_list">
      {/* <Table columns={fatherColumn} expandable={{ expandedRowRender }} scroll={{ y: 500 }} pagination={false} dataSource={tableDatas} /> */}
      <Spin spinning={tableLoading} style={{ width: '100%', height: '100%' }} className="spin_loaing">
        <div className="table_list_content">
          <Table
            columns={fatherColumn}
            scroll={{ y: 500 }}
            rowKey={record => record.lotId}
            expandable={{ expandedRowRender }}
            // loading={tableLoading}
            pagination={false}
            dataSource={fathertableDatas}
          />
        </div>

        <div className="table_list_footer">
          <Pagination current={page} total={total} showSizeChanger={false} pageSize={pageSize} onChange={(page, pageSize) => handleChangePage(page, pageSize)} />
        </div>
      </Spin>
    </div>
  );
};
export default TableLists;
